<template>
  <div class="search-result">
    <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
      <van-cell
        v-for="(article, index) in list"
        :key="index"
        :title="article.title"
        :to="{
          // 跟绝路由名称进行跳转
          name: 'article',

          // 传递路由动态参数
          params: {
            // 属性名：路由路径中设计的动态参数名称
            articleId: article.art_id
          }
        }"
      />
    </van-list>
  </div>
</template>

<script>
import { getSearchResults } from '@/api/search'
export default {
  name: 'SearchResult',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false, // 控制加载
      page: 1,
      perPage: 10
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  // 方法集合
  methods: {
    async onLoad() {
      // 1.请求获取数据
      const { data } = await getSearchResults({
        page: this.page,
        per_page: this.perPage,
        q: this.searchText
      })

      // 2.将数据放到数据列表中
      const { results } = data.data
      this.list.push(...results)

      // 3.关闭本次的loading
      this.loading = false

      // 4.判断是否还有数据
      if (results.length) {
        // 如果有，则更新获取下一页数据的页码
        this.page++
      } else {
        // 如果没有，则把finished 设置为true关闭加载更多
        this.finished = true
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-result {
  position: fixed;
  left: 0;
  right: 0;
  top: 108px;
  bottom: 0;
  overflow-y: auto;
}
</style>
